package com.genghis.ptas.util;

import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.scorm.entity.NodesInfo;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.*;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class UploadZipAndUNZip {


    //上传文件并返回文件上传后的路径
    public String uploadFile(HttpServletRequest request, CommonsMultipartFile upFile, String upPath) {
        try {
            if (!upFile.isEmpty()) {
                //得到上传SCORM压缩包的路径
                String realPath = request.getSession().getServletContext().getRealPath(upPath);
                System.out.println("realPath:" + realPath);
                //得到上传文件名
                String fileName = upFile.getOriginalFilename();
                InputStream inputStream = upFile.getInputStream();

                //上传的文件名，不带后缀
                String name = fileName.substring(0, fileName.lastIndexOf('.'));
                //以上传的文件名为名建立新文件夹
                File file = new File(realPath + "\\" + name);
                if (!file.exists()) {
                    file.mkdirs();
                }
                System.out.println("file path::::" + file.getAbsolutePath());
                String path = file.getAbsolutePath() + "\\" + fileName;
                path=path.replaceAll("\\\\","/");
                System.out.println("path:" + path);
                byte data[] = new byte[1024];
                int len = 0;
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }

                fileOutputStream.close();
                inputStream.close();

                return path;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //接收完整路径名
    public void unZip(String fileName) {
        String filePath = fileName.substring(0, fileName.lastIndexOf("/") + 1);
        try {
            ZipFile zipFile = new ZipFile(fileName);
            Enumeration emu = zipFile.entries();

            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();

                //判断是不是目录
                if (entry.isDirectory()) {
                    new File(filePath + entry.getName()).mkdirs();
                    continue;
                }

                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                File file = new File(filePath + entry.getName());

                //如果父目录不存在，先建立
                File parent = file.getParentFile();
                if (parent != null && (!parent.exists())) {
                    parent.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);

                int count;
                byte data[] = new byte[1024];
                while ((count = bis.read(data, 0, 1024)) != -1) {
                    bos.write(data, 0, count);
                }

                bos.flush();
                bos.close();
                bis.close();

            }

            zipFile.close();
        } catch (Exception e) {
        }
    }



    public List<NodesInfo> analyzeXml(String url) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        //得到一个Xpath对象
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expression = xpath.compile("/manifest/organizations/organization");
        //得到一个输入对象
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new File(url));
        NodeList nodeChapterList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
        //获得课件章路径
        List<NodesInfo> nodesInfos = new LinkedList<NodesInfo>();
        for (int i = 0; i < nodeChapterList.getLength(); i++) {
            NodesInfo nodesInfo = new NodesInfo();
            Element element = (Element) nodeChapterList.item(i);
            nodesInfo.setNodeId(element.getAttribute("identifier"));
            NodeList nodeList = element.getElementsByTagName("title");
            if (nodeList.item(0) != null) {
                nodesInfo.setNodeTitle(nodeList.item(0).getTextContent());
            }
            nodesInfo.setShowNodeType(element.getTagName());
            nodesInfo.setParentId("1");
            nodesInfo.setUrl("");
            nodesInfos.add(nodesInfo);
            //获得课件节路径
            getElement(element, nodesInfos, url, document);
        }
        return nodesInfos;
    }


    private void getElement(Element element, List<NodesInfo> nodesInfos, String url, Document document) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        NodeList nodes = element.getChildNodes();
        String scoPath = url.substring(0, url.indexOf(DictConstant.IMSMANIFEST));
        for (int i = 0; i < nodes.getLength(); i++) {
            if (nodes.item(i).getNodeName().equals("item")) {
                getElement((Element) nodes.item(i), nodesInfos, url, document);
                Element element1 = (Element) nodes.item(i);
                NodesInfo nodesInfo = new NodesInfo();
                NodeList nodeList = element1.getElementsByTagName("title");
                if (nodeList.item(0) != null) {
                    nodesInfo.setNodeTitle(nodeList.item(0).getTextContent());
                }
                nodesInfo.setShowNodeType(element1.getTagName());
                nodesInfo.setParentId(element.getAttribute("identifier"));
                nodesInfo.setNodeId(element1.getAttribute("identifier"));
                if (element1.getAttribute("identifierref") != "") {
                    nodesInfo.setUrl(scoPath + getUrl(element1.getAttribute("identifierref"), document));
                }
                nodesInfos.add(nodesInfo);
            }
        }
    }

    //获取路径
    private String getUrl(String identifier, Document document) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        //得到一个Xpath对象
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expression = xpath.compile("/manifest/resources/resource[@identifier='" + identifier + "']");
        //得到一个输入对象
        Element element = (Element) expression.evaluate(document, XPathConstants.NODE);
        //获取路径
        return element.getAttribute("href");
    }
}